<template>
  <a-row>
    <a-col :span="24">
      <a-descriptions :column="2">
        <a-descriptions-item label="采购批次">
          {{detail.batchNo}}

          <a-tag color="red" v-if="detail.isSettle === 0">未结清</a-tag>
          <a-tag color="#87d068" v-else-if="detail.isSettle === 1">已结清</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="交易金额(元)">
          {{detail.totalAmount}}

          <span>[已收票:{{checkData(detail.totalAmountReceived)}}；未收票:{{checkData(detail.totalAmountUnreceived)}}]</span>
        </a-descriptions-item>

        <a-descriptions-item label="油费金额(元)">
          {{detail.oilAmount}}

          <span>[已收票:{{checkData(detail.oilAmountReceived)}}；未收票:{{checkData(detail.oilAmountUnreceived)}}]</span>
        </a-descriptions-item>
        <a-descriptions-item label="运费金额(元)">
          {{detail.freightAmount}}

          <span>[已收票:{{checkData(detail.freightAmountReceived)}}；未收票:{{checkData(detail.freightAmountUnreceived)}}]</span>
        </a-descriptions-item>
      </a-descriptions>
    </a-col>
    <a-col :span="24">
      <a-table size="middle" :columns="columns" :data-source="detail.list" :pagination="false" rowKey="invoiceId">
        <template
          v-for="col in ['invoiceNo', 'amount', 'type', 'invoiceDate']"
          :slot="col"
          slot-scope="text, record"
        >
          <div :key="col">
            <a-input v-if="col === 'invoiceNo'" :value="text" @change="e => handleChange0(e.target.value, record.invoiceId, col)"/>
            <a-input-number v-else-if="col === 'amount'" :value="text" @change="value => handleChange(value, record.invoiceId, col)"/>
            <a-select v-else-if="col === 'type'" :value="text" class="selectWidth" @change="value => handleChange(value, record.invoiceId, col)">
              <a-select-option :key="1">油费</a-select-option>
              <a-select-option :key="2">运费</a-select-option>
              <!-- <a-select-option :key="3">加油卡</a-select-option> -->
            </a-select>
            <a-date-picker v-else-if="col === 'invoiceDate'" :defaultValue="text?moment(text):text" @change="(d, dt) => handleChange(dt, record.invoiceId, col)"/>
          </div>
        </template>
        <template slot="opt" slot-scope="record">
          <a @click="() => deleteIt(record.invoiceId)">删除</a>
        </template>
      </a-table>
      <a-col :span="24">
        <a-button style="width: 100%; margin: 10px 0" type="dashed" @click="handleAdd">+ 添加发票</a-button>
        <a-button style="width: 100%;" type="primary" @click="handleSave" :loading='loading'>提交发票</a-button>
      </a-col>
    </a-col>
  </a-row>
</template>

<script>
import moment from 'moment'
import {queryPurchaseDetail, purchaseId} from '@/api/landCenter'

export default {
  name: 'purchase-detail',
  props: ['id'],
  data () {
    return {
      detail: {
        list: []
      },
      columns: [
        {
          title: '发票号',
          dataIndex: 'invoiceNo',
          scopedSlots: { customRender: 'invoiceNo' }
        },
        {
          title: '发票金额(元)',
          dataIndex: 'amount',
          scopedSlots: { customRender: 'amount' }
        },
        {
          title: '类型',
          dataIndex: 'type',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '日期',
          dataIndex: 'invoiceDate',
          scopedSlots: { customRender: 'invoiceDate' }
        },
        {
          title: '操作',
          width: '50px',
          scopedSlots: {customRender: 'opt'}
        }
      ],
      loading: false
    }
  },
  methods: {
    moment,
    init () {
      if (this.id) {
        queryPurchaseDetail({purchaseId: this.id}).then(rsp => {
          this.detail = rsp.data
        })
      } else {
        this.detail = {list: []}
        this.loading = false
      }
    },
    checkData (value) {
      return (!value ? '--' : value)
    },
    handleAdd () {
      if (!this.$root._bc.createInvoice) {
        this.$message.error('您无此权限！')
        return
      }
      const newData = {
        invoiceId: -1 * Math.floor((Math.random() * 10000)),
        invoiceNo: '',
        amount: '',
        type: 1,
        invoiceDate: null
      }
      this.detail.list = [...this.detail.list, newData]
    },
    deleteIt (key) {
      if (!this.$root._bc.createInvoice) {
        this.$message.error('您无此权限！')
        return
      }
      const newData = [...this.detail.list]
      const result = newData.filter(item => key !== item.invoiceId)
      this.detail.list = result
    },
    handleChange0 (value, key, column) {
      const newData = [...this.detail.list]
      const target = newData.filter(item => key === item.invoiceId)[0]
      if (target) {
        target[column] = value.replace(/[^0-9a-zA-Z]/g, '')
        this.detail.list = newData
      }
    },
    handleChange (value, key, column) {
      const newData = [...this.detail.list]
      const target = newData.filter(item => key === item.invoiceId)[0]
      if (target) {
        target[column] = value
        this.detail.list = newData
      }
    },
    handleSave () {
      if (!this.$root._bc.createInvoice) {
        this.$message.error('您无此权限！')
        return
      }
      this.loading = true
      const list = []

      // 必填
      this.detail.list.map((obj, index, arr) => {
        if (obj.invoiceNo && obj.amount && obj.type && obj.invoiceDate) {
          list.push(obj)
        } else {
          return false
        }
      })

      if (this.detail.list.length !== list.length) {
        this.$message.error('发票信息填写不完整，请检查')
        this.loading = false
      } else {
        purchaseId({
          purchaseId: this.id,
          list
        }).then(rsp => {
          this.$message.success('提交成功')
          this.init()
          this.loading = false
        }).catch(() => { this.loading = false })
      }
    }
  },
  watch: {
    id () {
      this.init()
    }
  },
  mounted () {
    this.init()
  }
}
</script>

<style lang="less" scoped>

</style>
